﻿using Cxuu.Common;
using Cxuu.Models;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Cxuu.Repository
{
    [AppService]
    public class ArticleExamineRepository : BaseRepository<ArticleExamine, PetaPocoContext>
    {

        public ArticleExamineRepository(PetaPocoContext petaPocoContext) : base(petaPocoContext) { }


        /// <summary>
        /// 统计信息总量
        /// </summary>
        /// <returns></returns>
        public async Task<long> CountExamineAsync(int userId)
        {

            long count = await CreateDAO().ExecuteScalarAsync<long>("SELECT count(1) FROM cxuu_article_examine where UserId = @0 AND Status = 0;",userId);
            return count;
        }

        /// <summary>
        /// 编辑使用  查询一条需要自己审核的信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ViewExamine> GetEditByAidAsync(int id)
        {
            Sql sql = Sql.Builder;
            sql.Select("userpost.Nickname,user.Nickname as Examine,dept.DeptName,examine.*")
                 .From("cxuu_article_examine as examine")
                 .LeftJoin("cxuu_admin_user as userpost").On("examine.PostId=userpost.Id");
            sql.LeftJoin("cxuu_admin_user as user").On("examine.UserId=user.Id");
            sql.LeftJoin("cxuu_admin_dept as dept").On("dept.Id=user.DeptId");
            sql.Where("examine.Aid =@0", id);
            return await CreateDAO().FirstOrDefaultAsync<ViewExamine>(sql);
        }

        /// <summary>
        /// 编辑使用  查询一条审核信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ViewExamine> GetEditByIdAsync(int id)
        {
            Sql sql = Sql.Builder;
            sql.Select("userpost.Nickname,user.Nickname as Examine,dept.DeptName,examine.*")
                 .From("cxuu_article_examine as examine")
                 .LeftJoin("cxuu_admin_user as userpost").On("examine.PostId=userpost.Id");
            sql.LeftJoin("cxuu_admin_user as user").On("examine.UserId=user.Id");
            sql.LeftJoin("cxuu_admin_dept as dept").On("dept.Id=user.DeptId");
            sql.Where("examine.Id =@0", id);
            return await CreateDAO().FirstOrDefaultAsync<ViewExamine>(sql);
        }
        /// <summary>
        /// 编辑使用 查询一条 审核文件内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ViewArtExamine> GetEditArticleAsync(int aid)
        {
            Sql sql = Sql.Builder;
            sql.Select("article.Title,content.Content,article.Id as ArtId")
                 .From("cxuu_article as article")
                .LeftJoin("cxuu_article_content as content").On("content.Aid=article.Id");
            sql.Where("article.Id =@0", aid);
            return await CreateDAO().FirstOrDefaultAsync<ViewArtExamine>(sql);
        }
        public async Task<ViewArtExamine> GetArtNoContentAsync(int aid)
        {
            Sql sql = Sql.Builder;
            sql.Select("Title,Id as ArtId,Uid as ArtUserId")
                 .From("cxuu_article");
            sql.Where("Id =@0", aid);
            return await CreateDAO().FirstOrDefaultAsync<ViewArtExamine>(sql);
        }

        /// <summary>
        /// 查询当前文件流转列表
        /// </summary>
        /// <param name="aid"></param>
        /// <returns></returns>
        public async Task<List<ViewArticleExamine>> GetExamineingAsync(int aid)
        {
            Sql sql = Sql.Builder;
            sql.Select("article.Title,userpost.Nickname,user.Nickname as Examine,dept.DeptName,examine.*")
                 .From("cxuu_article_examine as examine")
                 .LeftJoin("cxuu_admin_user as userpost").On("examine.PostId=userpost.Id");
            sql.LeftJoin("cxuu_admin_user as user").On("examine.UserId=user.Id");
            sql.LeftJoin("cxuu_article as article").On("examine.Aid=article.Id");
            sql.LeftJoin("cxuu_admin_dept as dept").On("dept.Id=user.DeptId");
            sql.Where("examine.Aid =@0", aid);
            return await CreateDAO().FetchAsync<ViewArticleExamine>(sql);
        }

        /// <summary>
        /// 获取列表 
        /// </summary>
        public async Task<Page<ViewArticleExamine>> GetListAsync(ArticleExamineQuery articleQuery)
        {
            Sql sql = Sql.Builder;
            sql.Select("article.Title,user.Nickname,userexa.Nickname as Examine,dept.DeptName,examine.*")
                .From("cxuu_article_examine as examine")
                .LeftJoin("cxuu_article as article").On("article.Id = examine.Aid");
            sql.LeftJoin("cxuu_admin_user user").On("examine.PostId=user.Id");
            sql.LeftJoin("cxuu_admin_user userexa").On("examine.UserId=userexa.Id");
            sql.LeftJoin("cxuu_admin_dept as dept").On("dept.Id=user.DeptId");

            if (articleQuery.PostId > 0)
                sql.Where("examine.PostId =@0", articleQuery.PostId);
            else
                sql.Where("examine.UserId =@0", articleQuery.UserId);

            if (articleQuery.Status != -1)
                sql.Where("examine.Status = @0", articleQuery.Status);

            if (articleQuery.Pass != -1)
                sql.Where("examine.Pass = @0", articleQuery.Pass);

            if (!string.IsNullOrEmpty(articleQuery.NickName))
                sql.Where("user.Nickname like @0", "%" + articleQuery.NickName + "%");

            if (!string.IsNullOrEmpty(articleQuery.Title))
                sql.Where("article.Title like @0", "%" + articleQuery.Title + "%");

            if (!string.IsNullOrEmpty(articleQuery.Remarks))
                sql.Where("article.Remarks like @0", "%" + articleQuery.Remarks + "%");

            if (!string.IsNullOrEmpty(articleQuery.Orderby))
                sql.OrderBy("examine." + articleQuery.Orderby);

            return await CreateDAO().PageAsync<ViewArticleExamine>(articleQuery.Page, articleQuery.Limit, sql);
        }


        /// <summary>
        /// 插入或更新一条信息
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public async Task<int> InsertOrUpdateAsync(ViewArticleExamine article)
        {
            var dao = CreateDAO();

            Sql sql = Sql.Builder;
            sql.Select("*").From("cxuu_article_examine");
            sql.Where("PostId =@0", article.PostId);
            sql.OrderBy("Id desc");
            ArticleExamine checkTime = await CreateDAO().FirstOrDefaultAsync<ArticleExamine>(sql);

            if (checkTime != null)
            {
                TimeSpan secondSpan = new(DateTime.Now.Ticks - checkTime.InsertTime.Ticks);
                if (secondSpan.TotalSeconds < 15)
                {
                    return 401;
                }
            }

            if (article.Aid < 1) return 0;

            List<ViewArticleExamine> articleList = await GetExamineingAsync(article.Aid);
            if (articleList.Exists(t => t.PostId == article.UserId))
            {
                return 405;
            }

            ArticleExamine res = await GetAsync(article.Id > 0 ? article.Id : 0);

            if (res != null && res.Pass == (int)ExaminePassTypeEnum.Type.已办结)
            {
                return 400;
            }

            if (res != null && res.UserId == article.UserId)
                return 403;
            if (res != null && article.Aid == res.Aid && article.PostId == res.PostId)
            {
                res.UserId = article.UserId;
                return 0 < await dao.UpdateAsync(res) ? 101 : 0;
            }
            else
            {
                ArticleExamine articleExamine = new()
                {
                    Aid = article.Aid,
                    InsertTime = DateTime.Now,
                    Status = 0,
                    PostId = article.PostId,
                    UserId = article.UserId,
                };
                return null != await dao.InsertAsync(articleExamine) ? 100 : 0;
            }
        }

        /// <summary>
        /// 审核一个文件
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public async Task<int> EditPostAsync(ArticleExamine article)
        {
            var dao = CreateDAO();
            int id = article.Id > 0 ? article.Id : 0;
            ArticleExamine res = await GetAsync(id);
            if (res != null)
            {
                res.Pass = article.Pass;
                res.Status = 1;
                res.ExaTime = DateTime.Now;
                res.Remarks = article.Remarks;
                return await dao.UpdateAsync(res);
            }
            else
            {
                return 0;
            }
        }
    }
}
